package pref.junx.flybird.app;

import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import org.kymjs.kjframe.utils.PreferenceHelper;

import pref.junx.flybird.model.User;
import pref.junx.flybird.util.GsonUtils;

/**
 * Created by JunX on 17/5/12.
 */

public class AppContext extends Application {

    public static final String USER = "user";
    public static final String USERINFO = "userinfo";

    // 服务器地址
    public static final String HOST_URL = "http://www.junxonline.com";

    // 当前引用
    private static AppContext instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    // 获取AppContext
    public static AppContext getInstance() {
        return instance;
    }

    // 保存用户信息
    public void saveUserInfo(User user) {

        if(null != user) PreferenceHelper.write(getApplicationContext(), USER, USERINFO, GsonUtils.getGson().toJson(user));
    }

    // 获取用户信息
    public User getUserInfo() {

        String userInfoString = PreferenceHelper.readString(getApplicationContext(), USER, USERINFO, null);
        if(null != userInfoString) return GsonUtils.getGson().fromJson(userInfoString, User.class);
        return null;
    }

    // 清除用户信息
    public void cleanUserInfo() {
        PreferenceHelper.remove(getApplicationContext(), USER, USERINFO);
    }

    /**
     * 判断网络是否可用
     * @param context
     */
    public static Boolean isNetworkReachable(Context context) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo current = connectivityManager.getActiveNetworkInfo();
        if (current == null) return false;
        return (current.isAvailable());
    }

}
